<template>
  <div class="content">
    <div class="block">
      <div
        class="title_wrap"
        :class="isShowExternalVideo ? 'title_background' : ''"
      >
        <div v-if="isShowExternalVideo" class="view_mode_wrap">
          <div
            :class="listFlag === 4 ? 'view_mode_checked' : 'view_mode'"
            @click="setListType(4)"
          >
            4
          </div>
          <div
            :class="listFlag === 6 ? 'view_mode_checked' : 'view_mode'"
            @click="setListType(6)"
          >
            6
          </div>
          <div
            v-if="false"
            :class="listFlag === 9 ? 'view_mode_checked' : 'view_mode'"
            @click="setListType(9)"
          >
            9
          </div>
          <div
            v-if="false"
            :class="listFlag === 16 ? 'view_mode_checked' : 'view_mode'"
            @click="setListType(16)"
          >
            16
          </div>
        </div>

        <div class="list_menu_wrap">
          <span
            class="menu_left"
            :class="[videoFlag === 0 ? 'title_selected' : '']"
            @click="setVideoType(0)"
            >巢外监控</span
          >
          <span
            class="menu_center"
            :class="[videoFlag === 1 ? 'title_selected' : '']"
            @click="setVideoType(1)"
            >巢内监控</span
          >
          <span
            class="menu_right"
            :class="[videoFlag === 2 ? 'title_selected' : '']"
            @click="setVideoType(2)"
            >实时图传</span
          >
        </div>
        <svg-icon
          v-if="isShowExternalVideo"
          class="external-icon"
          icon-class="external-link-in"
          @click="externalMultiVideo()"
        />
        <svg-icon
          v-else
          class="external-icon"
          icon-class="external-link"
          @click="externalMultiVideo()"
        />
      </div>
      <div
        v-if="isShowList && selectNestList.length !== 0"
        class="list_wrap"
        :class="getListStyle()"
      >
        <div
          v-for="(item, index) in selectNestList"
          :key="index"
          class="video_wrap"
        >
          <video-comp
            :auto-play="true"
            :video-name="item.nest_name"
            :video-url="getUrlByTag(item)"
            :nest-info="item"
            :weather-info="item.weather"
            :is-flying="false"
            @showShareForm="openShareForm(item)"
          />
        </div>
      </div>
      <div
        v-if="selectNestList.length === 0"
        style="margin-top: 200px; flex: 1"
      >
        暂无视频
      </div>
      <el-pagination
        v-if="isShowList"
        class="pagination"
        :style="{ alignSelf: isShowExternalVideo ? 'center' : 'flex-end' }"
        small
        layout="total,prev, pager, next"
        :page-size="listFlag"
        :total="pageInfo.showTotal"
        :current-page="pageInfo.currentPage"
        :pager-count="5"
        @current-change="handleCurrentChange"
      />
      <!-- 分享功能 -->
      <div
        v-if="showShareFlag && selectedVideoItem && selectedVideoItem.shareUrl"
        class="shareUrlForm"
      >
        <div class="shareFormTitle">
          <div class="title">直播分享：{{ selectedVideoItem.nest_name }}</div>
          <svg-icon
            class="closeIcon"
            icon-class="close"
            @click="closeShareForm"
          />
        </div>

        <div class="shareBlock">
          <div class="shareTitle">分享链接</div>
          <div class="shareUrl">{{ selectedVideoItem.shareUrl }}</div>
          <div class="shareButton" @click="copyUrl">复制链接</div>
        </div>
        <div class="shareBlock">
          <div class="shareTitle">分享二维码</div>
          <img
            ref="shareQRCode"
            class="shareImg"
            :src="selectedVideoItem.shareImg"
          />
          <div class="shareButton" @click="downloadQRCode">下载二维码</div>
        </div>
        <div class="sharePeriod">分享有效期至：2023-11-24 11:59:06</div>
      </div>
    </div>
  </div>
</template>

<script>
import VideoComp from "@/views/components/tab-views/baseComps/VideoComp";

export default {
  components: { VideoComp },
  data() {
    return {
      isShowExternalVideo: false,
      value1: null,
      value2: null,
      colors: ["#99A9BF", "#F7BA2A", "#ff5500"], // 等同于 { 2: '#99A9BF', 4: { value: '#F7BA2A', excluded: true }, 5: '#FF9900' }
      //
      videoFlag: 0, // 视频类型：机巢外，内，飞行
      listFlag: 4, // 列表显示格式  isShowExternalVideo 可选 4.9.16;未展开时为4
      nestList: [],
      isShowList: true, // 主要用于刷新列表
      pageInfo: {
        // 页码信息
        showTotal: 0,
        currentPage: 1,
        videoTotal: 0,
        innerVideoTotal: 0,
        flightVideoTotal: 0,
      },
      allData: {
        // 所有列表数据
        nestList: [],
        innerNestList: [],
        workingNestList: [],
      },
      // 分享功能
      showShareFlag: true,
      selectedVideoItem: [],

      selectNestList: [], // 选中的机场
    };
  },
  watch: {
    pageInfo: {
      handler(newVal, oldVal) {
        this.getNestList();
      },
      immediate: true,
      deep: true,
    },
    isShowExternalVideo: {
      handler(newVal, oldVal) {
        this.getNestList();
      },
      immediate: true,
      deep: true,
    },
    videoFlag: {
      handler(newVal, oldVal) {
        this.getNestList();
      },
      immediate: true,
      deep: true,
    },
    selectNestList: {
      handler(newVal, oldVal) {
        console.log("selectNestList", newVal, oldVal);
        let that = this;
        // 退出
        if (oldVal?.length > 0) {
          for (let nest of oldVal) {
            console.log("机场 退出socket");
            KBSocket?.io.emit("monitor", {
              nest_code: nest.nest_code,
              method: "exit",
            });
          }
        }
        // 加入
        if (newVal?.length > 0) {
          for (let nest of newVal) {
            console.log("加入socket");
            KBSocket?.io.emit("monitor", {
              nest_code: nest.nest_code,
              method: "join",
            });
          }
        }
      },
      immediate: true,
      deep: true,
    },
    isShowExternalVideo(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.resetList();
      }
      if (!newVal) {
        this.setListType(4);
      }
    },
    videoFlag(newVal, oldVal) {
      if (newVal !== oldVal) {
        if (newVal === 0) {
          this.pageInfo.showTotal = this.pageInfo.videoTotal;
          this.resetList();
        } else if (newVal === 1) {
          this.pageInfo.showTotal = this.pageInfo.innerVideoTotal;
          this.resetList();
        } else if (newVal === 2) {
          this.requestWorkingNest();
        }
        this.pageInfo.currentPage = 1;
      }
    },
    listFlag(newVal, oldVal) {
      if (newVal !== oldVal) {
        this.pageInfo.currentPage = 1;
        this.resetList();
      }
    },
  },
  mounted() {
    this.nestList = this.$store.getters.nestList;
    console.log("view2 nestList", this.nestList);
    this.requestWorkingNest();
    this.initBusEvent();
  },
  beforeDestroy() {
    let that = this;
    that.selectNestList = [];

    that.$bus.off("external_multi_video");
    that.$bus.off("work_nest_change");
  },
  methods: {
    resetList() {
      this.isShowList = false;
      //
      setTimeout(() => {
        this.isShowList = true;
        this.$forceUpdate();
      }, 10);
    },
    getListStyle() {
      if (!this.isShowExternalVideo) {
        return "list_1";
      }
      switch (this.listFlag) {
        case 4:
          return "list_4";
        case 6:
          return "list_6";
        case 9:
          return "list_9";
        case 16:
          return "list_16";
        default:
          return "list_4";
      }
    },
    /**
     *  受多个参数影响
     *  titleFlag 区别；内外飞行监控
     *  列表样式：单列,4,9,16
     *  还有pageNum
     */
    getNestList() {
      let that = this;
      const pageNum = that.pageInfo.currentPage - 1;
      const pageSize = that.isShowExternalVideo ? that.listFlag : 4;
      let typeList = [];
      //
      if (that.videoFlag === 0) {
        typeList = that.allData.nestList;
      } else if (that.videoFlag === 1) {
        typeList = that.allData.innerNestList;
      } else if (that.videoFlag === 2) {
        typeList = that.allData.workingNestList;
      }
      //
      let nestList = typeList.slice(
        pageNum * pageSize,
        (pageNum + 1) * pageSize
      );
      that.selectNestList = nestList;
    },

    handleCurrentChange(val) {
      this.pageInfo.currentPage = val;
      this.resetList();
    },
    // 获取工作中机巢
    requestWorkingNest() {
      // 单独请求工作中飞机，减少用户延迟
      let data = this.$store.getters.nestStateList;
      if (!data) return;
      // 1 删除维保机巢
      // {nest_code: "a5ecc6d1-7f2a-4020-90ac-4245e88bf076", nest_name: "衢江04-廿里镇-化工园区"}
      // const maintenanceNests = data.maintenance ? data.maintenance.list : []
      // const abnormalNests = data.abnormal ? data.abnormal.list : []
      // const offlineNests = data.offline ? data.offline.list : []
      const onlineNests = data.online ? data.online.list : [];
      const workingNests = data.flying ? data.flying.list : [];
      //
      const tempList = this.nestList.filter((item) => {
        for (let i = 0; i < onlineNests.length; i++) {
          if (onlineNests[i].nest_code === item.nest_code) {
            return true;
          }
        }
        for (let i = 0; i < workingNests.length; i++) {
          if (workingNests[i].nest_code === item.nest_code) {
            return true;
          }
        }
        return false;
      });
      //

      // 2 获取工作中机巢
      const workingCodes = workingNests.map((item) => {
        return { nest_code: item.nest_code };
      });
      for (let i = 0; i < tempList.length; i++) {
        tempList[i].flying = !!workingCodes.find((value, index, arr) => {
          return value.nest_code === tempList[i].nest_code;
        });
      }
      // 3 设置机巢列表
      this.allData.nestList = tempList;
      this.allData.innerNestList = tempList.filter((item) => {
        return item.inner_video_url;
      });
      this.allData.workingNestList = tempList.filter((item) => {
        return item.flying;
      });
      // 4  设置页码信息
      this.pageInfo.videoTotal = this.allData.nestList.length;
      this.pageInfo.innerVideoTotal = this.allData.innerNestList.length;
      this.pageInfo.flightVideoTotal = this.allData.workingNestList.length;
      //
      if (this.videoFlag === 0) {
        if (this.pageInfo.videoTotal == this.pageInfo.showTotal) {
          // console.log("一样的");
          return false;
        }
        this.pageInfo.showTotal = this.pageInfo.videoTotal;
      } else if (this.videoFlag === 1) {
        if (this.pageInfo.innerVideoTotal == this.pageInfo.showTotal) {
          // console.log("一样的");
          return false;
        }
        this.pageInfo.showTotal = this.pageInfo.innerVideoTotal;
      } else if (this.videoFlag === 2) {
        if (this.pageInfo.flightVideoTotal == this.pageInfo.showTotal) {
          // console.log("一样的");
          return false;
        }
        this.pageInfo.showTotal = this.pageInfo.flightVideoTotal;
      }
      console.log("view2 allData", this.allData);
      console.log("view2 pageInfo", this.pageInfo);
      this.resetList();
    },

    // 视频展开事件
    initBusEvent() {
      const that = this;
      that.$bus.on("work_nest_change", () => {
        this.requestWorkingNest();
      });
    },
    // 选择视频类型
    setVideoType(val) {
      if (val === this.videoFlag) return;
      this.videoFlag = val;
    },
    // 选择列表类型
    setListType(val) {
      if (val === this.listFlag) return;
      this.listFlag = val;
    },
    // 获取根据videoType 获取视频地址
    getUrlByTag(item) {
      if (!item) return "";
      if (this.videoFlag === 0) {
        return item.nest_video_url;
      } else if (this.videoFlag === 1) {
        return item.inner_video_url;
      } else if (this.videoFlag === 2) {
        // return item.flying ? item.flight_aircraft.aircraft_video_url : ''
        return item.flight_aircraft.aircraft_video_url;
      }
    },
    openShareForm(item) {
      // 检测type
      // console.log('showShareForm', this.getUrlByTag(item))
      // console.log('showShareForm', item)
      // //
      // this.showShareFlag = true
      // this.showShareUrl = this.getUrlByTag(item)
      // this.selectedVideoItem = item
      // this.selectedVideoItem.shareUrl = this.getUrlByTag(item)
      // // todo 获取地址
      // this.selectedVideoItem.shareImg = 'http://fsimage.guihuao.com/oper_log/push/1f35349ba28e0e5f7e45904210f8ae3c.png'
    },
    closeShareForm() {
      this.showShareFlag = true;
      this.selectedVideoItem = null;
    },
    copyUrl() {
      const input = document.createElement("input");
      input.value = this.selectedVideoItem.shareUrl;
      document.body.appendChild(input);
      input.select();
      document.execCommand("copy");
      document.body.removeChild(input);
      this.$message.success("复制成功");
    },
    downloadQRCode() {
      const name = new Date().getTime();
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      // crossorigin 是HTML5中新增的<img>标签属性
      // crossorigin属性有两个值可选：
      // anonymous:如果使用这个值的话就会在请求中的header中的带上origin属性，但请求不会带上cookie和其他的一些认证信息。
      // use-credentials:这个同时会在跨域请求中带上cookie和其他的一些认证信息。在使用这两个值时都需要server端在response的header中带上Access-Control-Allow-Credentials属性。可以通过server的配置文件来开启这个属性：server开启Access-Control-Allow-Credentials
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function () {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;

        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png");
        // 生成一个a元素
        var a = document.createElement("a");
        // 创建一个单击事件
        var event = new MouseEvent("click");

        // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
        a.download = name || "下载图片名称";
        // 将生成的URL设置为a.href属性
        a.href = url;

        // 触发a的单击事件
        a.dispatchEvent(event);
      };
      image.src = this.$refs.shareQRCode.getAttribute("src");
    },

    externalMultiVideo() {
      // 关闭机巢圈圈图层
      this.isShowExternalVideo = !this.isShowExternalVideo;
      this.$parent.isShowExternalVideo = this.isShowExternalVideo;
    },
  },
};
</script>

<style lang="scss" scoped>
* {
  caret-color: transparent;
}

.content {
  padding: 10px;
  color: white;
  height: 100%;
  width: 100%;
  text-align: center;
  position: relative;

  .block {
    height: 100%;
    display: flex;
    flex-direction: column;
    position: relative;

    .title_wrap {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .view_mode_wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;
        cursor: pointer;

        .view_mode {
          margin-right: 5px;
          width: 25px;
          height: 25px;
          line-height: 23px;
          text-align: center;
          border: #1cc1ff 1px solid;
        }

        .view_mode_checked {
          margin-right: 5px;
          width: 25px;
          height: 25px;
          line-height: 23px;
          text-align: center;
          background-color: #1cc1ff;
          border: #1c8edf 1px solid;
        }
      }

      .list_menu_wrap {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        cursor: pointer;
        color: white;
        margin: 0 10px;

        .menu_left {
          flex: 1;
          padding: 4px 8px;
          border-left: #1cc1ff 1px solid;
          border-top: #1cc1ff 1px solid;
          border-bottom: #1cc1ff 1px solid;
          border-radius: 6px 0 0 6px;
        }

        .menu_center {
          flex: 1;
          padding: 4px 8px;
          border: #1cc1ff 1px solid;
        }

        .menu_right {
          flex: 1;
          padding: 4px 8px;
          border-right: #1cc1ff 1px solid;
          border-top: #1cc1ff 1px solid;
          border-bottom: #1cc1ff 1px solid;
          border-radius: 0 6px 6px 0;
        }

        .title_selected {
          color: #1cc1ff;
        }
      }

      .external-icon {
        margin-left: 12px;
        width: 24px;
        height: 24px;
      }
    }

    .list_wrap {
      flex: 1;
      height: 0;
      //height: vh(900);
      display: grid;
      row-gap: 20px;
      column-gap: 20px;
      margin: auto;
      place-items: center;

      .video_wrap {
        width: 100%;
        height: 100%;
        background-color: black;
      }
    }

    .list_1 {
      width: 100%;
      grid-template-columns: 1fr;
      grid-template-rows: 1fr 1fr 1fr 1fr;
    }

    .list_4 {
      width: 90%;
      grid-template-columns: 1fr 1fr;
      grid-template-rows: 1fr 1fr;
    }

    .list_6 {
      width: 90%;
      grid-template-columns: 1fr 1fr 1fr;
      grid-template-rows: 1fr 1fr 1fr;
    }

    .list_9 {
      width: 90%;
      grid-template-columns: 1fr 1fr 1fr;
      grid-template-rows: 1fr 1fr 1fr;
    }

    .list_16 {
      width: 90%;
      grid-template-columns: 1fr 1fr 1fr 1fr;
      grid-template-rows: 1fr 1fr 1fr 1fr;
    }

    .pagination {
      margin-top: vh(30);
      align-self: flex-end;
      background-color: rgb(0, 0, 0, 0);

      ::v-deep .el-pagination__total {
        color: #eeeeee;
      }

      ::v-deep .el-pagination {
        background-color: rgb(0, 0, 0, 0);
      }

      ::v-deep .btn-prev {
        background-color: rgb(0, 0, 0, 0);
      }

      ::v-deep .el-icon {
        color: #eeeeee;
      }

      ::v-deep .btn-next {
        background-color: rgb(0, 0, 0, 0);
      }

      ::v-deep .number {
        background-color: rgb(0, 0, 0, 0);
        color: #eeeeee;
      }

      ::v-deep .active {
        color: dodgerblue;
      }

      ::v-deep .more {
        background-color: rgb(0, 0, 0, 0);
      }
    }
  }

  .shareUrlForm {
    position: fixed;
    top: 80px;
    left: 355px;
    width: 400px;
    background-color: rgba(5, 29, 40, 0.6);

    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: white;

    .shareFormTitle {
      position: relative;
      width: 100%;
      background-color: rgba(5, 29, 40, 1);
      padding: 10px 0;
      height: 40px;

      .title {
      }

      .closeIcon {
        position: absolute;
        right: 10px;
        top: 5px;
        width: 30px;
        height: 30px;
        cursor: pointer;
      }
    }

    .shareBlock {
      padding: 10px;
      width: 100%;

      .shareTitle {
        text-align: left;
      }

      .shareUrl {
        padding: 15px;
        color: lightgrey;
        text-align: left;
        word-break: break-all;
      }

      .shareImg {
        width: 200px;
        height: 200px;
        border: white 1px solid;
        margin: 10px;
      }

      .shareButton {
        margin: auto;
        width: 100px;
        padding: 3px 10px;
        border-radius: 4px;
        text-align: center;
        background-color: #1cc1ff;
        cursor: pointer;
      }
    }

    .sharePeriod {
      margin-top: 10px;
      margin-bottom: 30px;
    }
  }
}
</style>
